package com.peanut.baby.mvp.liveroom;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.devlibrary.util.FileUtil;
import com.tencent.mars.xlog.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by anonymouslystudio on 2017/7/25.
 */

public class AppVoicePlayer {
    private static final String TAG = RoomLectureFragment.class.getSimpleName();

    private static final int MSG_CACHE_READY        = 1;
    private static final int MSG_CACHE_EXCEPTION    = -1;


    private String      url;
    private boolean     isSelfViewPort;
    private View        container;
    private boolean     isPlaying = false;

    private MediaPlayer mediaPlayer;

    private ImageView               icon;

    private AnimationDrawable       iconDrawable;
    private OnAppVoicePlayListener  listener;
    private OnAppVoicePlayListener  lastListener;
    private boolean     isSpeakerOpened = true;
    private String      localCacheFile;
    private List<String> list = new ArrayList<>();
    private int currPlay = 0;

    private static AppVoicePlayer instance;

    private Handler handler = new Handler(Looper.getMainLooper()){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_CACHE_EXCEPTION:
                    Log.d(TAG,"msg cache exception");
                    if(listener != null){
                        listener.onException("下载音频文件失败");
                    }
                    break;
                case MSG_CACHE_READY:
                    Log.d(TAG,"msg cache success");
                    doPlay();
                    break;
            }
        }
    };

//    private static final class InstanceHolder{
//        public static AppVoicePlayer instance = new AppVoicePlayer();
//    }
    public static AppVoicePlayer getInstance(){
        if(instance == null){
            instance = new AppVoicePlayer();
        }
        return instance;
    }

    public void play(String url,boolean isSelfViewPort,View container,OnAppVoicePlayListener listener){
        Log.d(TAG,"play");
        releasePlayer();
        this.url = url;
        this.isSelfViewPort = isSelfViewPort;
        this.container = container;
        this.listener = listener;
        initViews();
        playVoice();
    }

    public void playList(List<String> urls, OnAppVoicePlayListener listener){
        if(this.list!= null && currPlay <this.list.size()){
            if(lastListener!=null)
                    lastListener.onInterrupt();
        }
        Log.d(TAG,"playList");
        releasePlayer();
        list = urls;
        this.url = urls.get(0);
        this.listener = listener;
        this.lastListener = listener;
        playVoice();
    }

    public void playVoice() {
        AudioManager audioManager = (AudioManager) InitManager.getInstance().getCtx().getSystemService(Context.AUDIO_SERVICE);
        mediaPlayer = new MediaPlayer();
        if (isSpeakerOpened) {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.setSpeakerphoneOn(true);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        } else {
            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
            // 把声音设定成Earpiece（听筒）出来，设定为正在通话中
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        }
        //first try local file
        File f = getLocalCachedFile();
        if(f != null){
            Log.d(TAG,"local cache file exists, start play cache");
            doPlay();
        }else{
            Log.d(TAG,"local cache file not exists, start download");
            startDownloadFile();
        }
//        try {
//
//            mediaPlayer.setDataSource(url);
//            mediaPlayer.prepareAsync();
//            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    mediaPlayer.release();
//                    mediaPlayer = null;
//                    iconDrawable.stop();
//                    if(isSelfViewPort){
//                        icon.setImageResource(R.drawable.ease_chatto_voice_playing_f3);
//                    }else{
//                        icon.setImageResource(R.drawable.ease_chatfrom_voice_playing_f3);
//                    }
//
//                    // stop play voice
//                    if (mediaPlayer != null) {
//                        mediaPlayer.stop();
//                        mediaPlayer.release();
//                    }
//                    isPlaying = false;
//                    url = "";
//                    if(listener != null){
//                        listener.onPlayFinished();
//                    }
//                }
//
//            });
//            isPlaying = true;
//            mediaPlayer.start();
//            iconDrawable.start();
//
//
//        } catch (Exception e) {
//            Log.d(TAG,"play audio exception: "+e.toString());
//            if(listener != null){
//                listener.onException(e.toString());
//            }
//        }
    }

    private void startDownloadFile(){
        new Thread(new Runnable() {
            @Override
            public void run() {
               boolean success = FileUtil.downloadFile(getLocalFilePath(), url);
                handler.sendMessage(handler.obtainMessage(success ? MSG_CACHE_READY : MSG_CACHE_EXCEPTION));
            }
        }).start();
    }

    private void doPlay(){
        try {
            if(list!=null&&list.size()>0&&currPlay==0)
                listener.onPlayStarted();
            mediaPlayer.setDataSource(getLocalFilePath());
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.d(TAG,"onError "+what+" "+extra);
                    return false;
                }
            });
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    isPlaying = true;
                    mediaPlayer.start();
                    if(iconDrawable!=null)
                        iconDrawable.start();

                }
            });
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    currPlay = currPlay+1;
                    if(list!=null && list.size()>0 && currPlay<list.size()){
                        url = list.get(currPlay);
                        mediaPlayer.reset();
                        startDownloadFile();
                    } else {
                        releasePlayer();
                        if (listener != null) {
                            listener.onPlayFinished();
                        }
                    }
                }

            });


        } catch (Exception e) {
            Log.d(TAG,"play audio exception: "+e.toString());
            if(listener != null){
                listener.onException(e.toString());
            }
        }
    }

    private File getLocalCachedFile(){
        String path = getLocalFilePath();
        File f = new File(path);
        if(f.exists() && f.isFile() && f.length() > 0){
            return f;
        }
        return null;
    }


    private void initViews(){
        if(container == null) return;
        icon = (ImageView) container.findViewById(R.id.play_icon);
        if(isSelfViewPort){
            icon.setImageResource(R.drawable.voice_to_icon);
        }else{
            icon.setImageResource(R.drawable.voice_from_icon);
        }
        iconDrawable = (AnimationDrawable) icon.getDrawable();
    }

    public boolean isPlaying(){
        return isPlaying;
    }

    public String getUrl(){
        return url;
    }

    private String getLocalFilePath(){
        if(TextUtils.isEmpty(localCacheFile)){
            localCacheFile = InitManager.getInstance().getVoiceDir()+ FileUtil.getNameByUrl(url);
            Log.d(TAG,"localCacheFile: "+localCacheFile);
        }

        return localCacheFile;
    }

    public void releasePlayer() {
        Log.d(TAG, "releasePlayer...");
        try {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.reset();
                mediaPlayer.release();
            }
            try {
                if(iconDrawable != null){
                    iconDrawable.stop();
                }

                if(icon != null){
                    if(isSelfViewPort){

                        icon.setImageResource(R.drawable.ease_chatto_voice_playing_f3);
                    }else{
                        icon.setImageResource(R.drawable.ease_chatfrom_voice_playing_f3);
                    }
                }
            } catch (Exception e) {
            }

            isPlaying = false;

        } catch (IllegalStateException e) {

        } finally {
            mediaPlayer = null;
            url = "";
            localCacheFile = "";
        }


    }

    public void onDestory(){
        Log.d(TAG,"onDestory");

        releasePlayer();
        instance = null;
    }



    public interface OnAppVoicePlayListener{
        void onException(String reason);
        void onPlayFinished();
        void onPlayStarted();
        void onInterrupt();
    }
}
